package com.yc.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Sokect 套接字
 * ServerSocket
 * QQ 聊天
 */
public class QQServer {

    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器启动:8888");
        // 等待客户端连接, 阻塞状态
        Socket socket = server.accept();

        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        Scanner scanner = new Scanner(System.in);

        new Thread() {
            public void run() {
                while (true) {
                    System.out.print("请输入:");
                    String msg = scanner.nextLine();  // 阻塞点
                    try {
                        out.write(msg.getBytes(StandardCharsets.UTF_8));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while (true) {
                    byte[] buffer = new byte[1024];
                    int count = 0;  // 阻塞点
                    try {
                        count = in.read(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String msg = new String(buffer, 0, count);
                    if (msg.matches("文件:[^:]+:\\d+")) {
                        recvFile(in, msg);
                    }


                    System.out.println("客户端说:" + msg);
                }
            }
        }.start();
    }

    /**
     * 扩展:  用户可以屏幕输入另存为的新的路径
     */

    public static void recvFile(InputStream in, String msg) {
        String[] items = msg.split(":");
        String filename = items[1];
        String sizeStr = items[2];
        long size = Long.parseLong(sizeStr);
        String defaultPath = "d:/";
        String filepath = defaultPath + filename;

        System.out.println("接收文件: " + filepath);

        try (FileOutputStream fos = new FileOutputStream(filepath)) {
            byte[] bytes = new byte[1024];
            int count;
            while (size > 0 && (count = in.read(bytes)) > -1) {
                fos.write(bytes, 0, count);
                size -= count;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}



